import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';

export async function GET(request: NextRequest) {
  try {
    // 从CSV文件解析计量单位数据
    const csvFilePath = path.join(process.cwd(), 'excel/06-21/计量单位定义表.csv');
    
    if (!fs.existsSync(csvFilePath)) {
      return NextResponse.json([]);
    }

    const csvContent = fs.readFileSync(csvFilePath, 'utf-8');
    const lines = csvContent.split('\n').filter(line => line.trim());
    
    // 解析CSV数据，转换为前端需要的格式
    const measurementUnits: Array<{ unit_class: string; unit_name: string; unit_symbol: string }> = [];
    
    // 从第三行开始解析（跳过标题行和列标题行）
    for (let i = 2; i < lines.length; i++) {
      const line = lines[i];
      const columns = line.split(',');
      
      // 每行有8列，每2列为一组 (计量类名, 计量单位)
      for (let j = 0; j < columns.length; j += 2) {
        const category = columns[j]?.trim();
        const unit = columns[j + 1]?.trim();
        
        if (category && unit && category !== '—' && unit !== '—') {
          measurementUnits.push({ 
            unit_class: category, 
            unit_name: unit,
            unit_symbol: unit // 使用 unit_name 作为 unit_symbol
          });
        }
      }
    }

    return NextResponse.json(measurementUnits);
  } catch (error: any) {
    console.error('获取计量单位失败:', error);
    return NextResponse.json({ error: error?.message || String(error) || '获取计量单位失败' }, { status: 500 });
  }
} 